package com.cloudwave.trailends.ui;

import java.text.DecimalFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.LinePoint;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.service.RidingService;
import com.cloudwave.trailends.utils.DateUtils;
import com.cloudwave.trailends.widget.dialog.ColaProgress;
import com.cloudwave.trailends.widget.view.CustomDialog;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.exception.DbException;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.RenrenSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

public class DetailActivity extends BaseActivity {
	private static final String TAG = "DetailActivity";
	private DecimalFormat df = new DecimalFormat("#0.00");
	
	private RidingLine rl = null;
	
	private ImageButton btnBack;
	private TextView tvTitle;
  	private ImageButton btnOK;
  	
  	private TextView tvLineTitle;
  	private ImageButton ibTitleEdit;
  	private TextView tvMileage;
    private TextView tvPoint;
    private TextView tvTotalTime;
    private TextView tvValidTime;
    private TextView tvPauseTime;
    
    private TextView tvMap;
    private TextView tvShare;
    
    
    private TextView tvMaxSpeed;
    private TextView tvCurSpeed;
    private TextView tvAvgSpeed;
//    private TextView tvMaxGpsSpeed;
//    private TextView tvAvgGpsSpeed;
    private TextView tvKcal;
    
    private TextView tvStartTime;
    private TextView tvEndTime;
    
    private View tvCurSpeedView1;
    private View tvCurSpeedView2;
    
    private TextView tvEndRiding;
    private TextView tvContinue;
    
    private boolean isDealEnd = false;  //是否成功结束骑记
    private boolean isUpadateOk = false;  //是否成功更新骑记
    
    private RidingReceiver ridingReceiver;
    
    private PopupWindow moreMenuPopup;
	private LinearLayout moreMenuLayout;
	private ListView moreMenuListView;
    private String moreMenuItem[] = { "编辑", "操作"};
    
    final UMSocialService Umeng = UMServiceFactory.getUMSocialService("com.umeng.share");
    
    private boolean waiteEnd = false;  //是否处于等待结束的状态
    private ColaProgress cp = null;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.detail);
		
		initView();
		
		Long id = getIntent().getLongExtra("rlId", 0);
		initData(id);
	}

	private void initView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		btnOK = (ImageButton) findViewById(R.id.btnOK);
		
		tvLineTitle = (TextView) findViewById(R.id.tvLineTitle);
		ibTitleEdit = (ImageButton) findViewById(R.id.ibTitleEdit);
		tvMileage = (TextView) findViewById(R.id.tvMileage);
		tvPoint = (TextView) findViewById(R.id.tvPoint);
		tvTotalTime = (TextView) findViewById(R.id.tvTotalTime);
		
		tvShare = (TextView) findViewById(R.id.tvShare);
		tvMap = (TextView) findViewById(R.id.tvMap);
		
		tvValidTime = (TextView) findViewById(R.id.tvValidTime);
		tvPauseTime = (TextView) findViewById(R.id.tvPauseTime);
		tvMaxSpeed = (TextView) findViewById(R.id.tvMaxSpeed);
		tvCurSpeed = (TextView) findViewById(R.id.tvCurSpeed);
		tvAvgSpeed = (TextView) findViewById(R.id.tvAvgSpeed);
//		tvMaxGpsSpeed = (TextView) findViewById(R.id.tvMaxGpsSpeed);
//		tvAvgGpsSpeed = (TextView) findViewById(R.id.tvAvgGpsSpeed);
		tvKcal = (TextView) findViewById(R.id.tvKcal);
		
		tvStartTime = (TextView) findViewById(R.id.tvStartTime);
		tvEndTime = (TextView) findViewById(R.id.tvEndTime);
		
		tvEndRiding = (TextView) findViewById(R.id.tvEndRiding);
		tvContinue = (TextView) findViewById(R.id.tvContinue);
		
		tvTitle.setText("详情");
		btnOK.setImageResource(R.drawable.btn_delete);
//		btnOK.setImageResource(R.drawable.img_actionitem_more_normal);
		
		tvCurSpeedView1 = (View) findViewById(R.id.tvCurSpeedView1);
		tvCurSpeedView2 = (View) findViewById(R.id.tvCurSpeedView2);
		
		if ( RidingService.now_rlId != 0 ) {
			tvContinue.setBackgroundResource(R.color.them_gray);
		}
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				endThis();
			}
		});
		
		ibTitleEdit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(DetailActivity.this, EditActivity.class);
				intent.putExtra("rlId", rl.getId());
				startActivityForResult(intent, 101);
			}
		});
		
		tvMap.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if ( rl.getTotalPoint() == 0 ) {
					Toast.makeText(DetailActivity.this, "这个骑记没有记录任何坐标点！", Toast.LENGTH_SHORT).show();
					return ;
				}
				Intent intent = new Intent(DetailActivity.this, PathViewActivity.class);
//				Intent intent = new Intent(DetailActivity.this, DetailChartActivity.class);
				intent.putExtra("rlId", rl.getId());
				startActivity(intent);
			}
		});
		
		tvShare.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				Toast.makeText(DetailActivity.this, "敬请期待...", Toast.LENGTH_SHORT).show();
				share();
			}
		});
		
		btnOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				btnOK.getTop();
//				int y = btnOK.getBottom() * 3 / 2;
//				int x = getWindowManager().getDefaultDisplay().getWidth() / 4;
//				showMoreMenuPopup(x, y);
				dialogDeleteRiding();
			}
		});
		
		tvEndRiding.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialogStopRiding();
			}
		});
		
		tvContinue.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				continueRiding();
			}
		});
	}
	
	private void initData(Long rlId) {
		
		if (rlId == null || rlId == 0) {
			Toast.makeText(DetailActivity.this, "参数错误~_~", Toast.LENGTH_SHORT).show();
			Log.w(TAG, "没有接收到参数!");
			this.finish() ;
		}
		
		DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		try {
			rl = dbu.findById(RidingLine.class, rlId);
		} catch (DbException e) {
			Toast.makeText(DetailActivity.this, "加载骑记失败~_~", Toast.LENGTH_SHORT).show();
			Log.w(TAG, "查询记录数据异常:", e);
			this.finish() ;
		}
		
		if ( rl == null ) {
			Toast.makeText(DetailActivity.this, "骑记不存在或已经删除~_~", Toast.LENGTH_SHORT).show();
			this.finish() ;
		}
		
		tvLineTitle.setText(rl.getTitle());
		tvMileage.setText(df.format(rl.getTotalMileage() / 1000));
		
		tvStartTime.setText(DateUtils.format(rl.getStartTime(), "yyyy-MM-dd HH:mm"));
		if ( rl.getEndTime() != null ) {
			tvEndTime.setText(DateUtils.format(rl.getEndTime(), "yyyy-MM-dd HH:mm"));
		} else {
			tvEndTime.setText("......");
		}
		
		String tStr = this.getResources().getString(R.string.stat_times);
        int[] time = DateUtils.duration(rl.getTotalTime() * 1000);
        String tNewStr = String.format(tStr, time[1], time[2], time[3]);
		tvTotalTime.setText(tNewStr);
		
//		if ( rl.getTotalValidTime() > 0 ) {
//			String tStr2 = this.getResources().getString(R.string.stat_times);
//	        int[] time2 = DateUtils.duration(rl.getTotalValidTime() * 1000);
//	        String tNewStr2 = String.format(tStr2, time2[1], time2[2], time2[3]);
//			tvValidTime.setText(tNewStr2);
//			
//			long pauseTime = rl.getTotalTime()-rl.getTotalValidTime();
//			String tStr3 = this.getResources().getString(R.string.stat_times);
//	        int[] time3 = DateUtils.duration(pauseTime * 1000);
//	        String tNewStr3 = String.format(tStr3, time3[1], time3[2], time3[3]);
//			tvPauseTime.setText(tNewStr3);
//		} else {
//			tvValidTime.setText("--");
//			tvPauseTime.setText("--");
//		}
		
		String tStr2 = this.getResources().getString(R.string.stat_times);
        int[] time2 = DateUtils.duration(rl.getTotalValidTime() * 1000);
        String tNewStr2 = String.format(tStr2, time2[1], time2[2], time2[3]);
		tvValidTime.setText(tNewStr2);
		
		long pauseTime = rl.getTotalTime()-rl.getTotalValidTime();
		String tStr3 = this.getResources().getString(R.string.stat_times);
        int[] time3 = DateUtils.duration(pauseTime * 1000);
        String tNewStr3 = String.format(tStr3, time3[1], time3[2], time3[3]);
		tvPauseTime.setText(tNewStr3);
		
//		if ( rl.getMaxSpeed() == null || rl.getMaxSpeed().isInfinite() || rl.getMaxSpeed() == 0 ) {
//			if ( rl.getValidAvgSpeed() <= 0 ) {
//				tvMaxSpeed.setText("--");
//				tvAvgSpeed.setText("--");
//			} else {
//				tvMaxSpeed.setText(df.format(rl.getValidAvgSpeed()));
//				tvAvgSpeed.setText(df.format(rl.getValidAvgSpeed()));
//			}
//		} else {
//			tvMaxSpeed.setText(df.format(rl.getMaxSpeed()));
//			tvAvgSpeed.setText(df.format(rl.getValidAvgSpeed()));
//		}
		
		
		if ( rl.getMaxSpeed() == null || rl.getMaxSpeed().isInfinite() || rl.getMaxSpeed() == 0 ) {
			tvMaxSpeed.setText("--");
		} else {
			tvMaxSpeed.setText(df.format(rl.getMaxSpeed()));
		}
		tvAvgSpeed.setText(df.format(rl.getValidAvgSpeed()));
		
		if ( rl.getMaxGpsSpeed() == null || rl.getMaxGpsSpeed().isInfinite() || rl.getMaxGpsSpeed() == 0 ) {
			tvMaxSpeed.setText("--");
		} else {
			tvMaxSpeed.setText(df.format(rl.getMaxGpsSpeed()));
		}
		
		if ( rl.getAvgGpsSpeed() == null || rl.getAvgGpsSpeed().isInfinite() || rl.getAvgGpsSpeed() == 0 ) {
			tvAvgSpeed.setText("--");
		} else {
			tvAvgSpeed.setText(df.format(rl.getAvgGpsSpeed()));
		}
		
//		if ( rl.getMaxGpsSpeed() == null || rl.getMaxGpsSpeed().isInfinite() || rl.getMaxGpsSpeed() == 0 ) {
//			tvMaxGpsSpeed.setText("--");
//		} else {
//			tvMaxGpsSpeed.setText(df.format(rl.getMaxGpsSpeed()));
//		}
//		
//		if ( rl.getAvgGpsSpeed() == null || rl.getAvgGpsSpeed().isInfinite() || rl.getAvgGpsSpeed() == 0 ) {
//			tvAvgGpsSpeed.setText("--");
//		} else {
//			tvAvgGpsSpeed.setText(df.format(rl.getAvgGpsSpeed()));
//		}
		
		
		tvPoint.setText(String.valueOf(rl.getTotalPoint()));
		
		User user = ((AppContext) getApplication()).loadLoginUser();
		
		if ( user == null || user.getWeight() == null 
				|| user.getWeight() == 0 ) {
			tvKcal.setText("请先设置体重!");
		} else {
			tvKcal.setText(df.format(rl.getKcal()));
		}
		
		if ( rl.getId().intValue() != RidingService.now_rlId ) {
			tvCurSpeedView1.setVisibility(View.GONE);
			tvCurSpeedView2.setVisibility(View.GONE);
		} else {
			tvCurSpeed.setText("--");
		}
		
		long now_rlId = RidingService.now_rlId;
		if (now_rlId != 0 && now_rlId == rl.getId().intValue() ) {  //是当前骑记
			btnOK.setVisibility(View.GONE);  //不能删除
			tvContinue.setVisibility(View.GONE);  //不能继续
		} else {
			if ( rl.getEndTime() == null ) {  //骑记没有结束
				btnOK.setVisibility(View.VISIBLE);
				tvContinue.setVisibility(View.VISIBLE);
				tvEndRiding.setVisibility(View.VISIBLE);
			} else {
				btnOK.setVisibility(View.VISIBLE);
				tvContinue.setVisibility(View.GONE);
				tvEndRiding.setVisibility(View.GONE);
			}
		}
	}
	
	private void showMoreMenuPopup(int x, int y) {
		moreMenuLayout = (LinearLayout) LayoutInflater.from(DetailActivity.this).inflate(
				R.layout.dialog_more_menu, null);
		moreMenuListView = (ListView) moreMenuLayout.findViewById(R.id.lv_dialog_item);
		moreMenuListView.setAdapter(new ArrayAdapter<String>(DetailActivity.this,
				R.layout.dialog_more_menu_item, R.id.tv_text, moreMenuItem));

		moreMenuPopup = new PopupWindow(DetailActivity.this);
		moreMenuPopup.setBackgroundDrawable(new BitmapDrawable());
		moreMenuPopup.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
		moreMenuPopup.setHeight(300);
		moreMenuPopup.setOutsideTouchable(true);
		moreMenuPopup.setFocusable(true);
		moreMenuPopup.setContentView(moreMenuLayout);
		moreMenuPopup.showAtLocation(findViewById(R.id.detail), Gravity.LEFT
				| Gravity.TOP, 240, y);
		
		moreMenuListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				moreMenuPopup.dismiss();
				moreMenuPopup = null;
			}
		});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		registerReceiver();
	}
	
	private void registerReceiver() {
		ridingReceiver = new RidingReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(RidingService.UPDATE_STAT);
		filter.addAction(RidingService.UPDATE_SPEED);
		filter.addAction(RidingService.RL_UPDATE);
		registerReceiver(ridingReceiver, filter);
	}
	
	private void share() {
		if ( RidingService.now_rlId != 0 && 
				(rl.getRemoteId() == RidingService.now_rlId)) {
			Toast.makeText(DetailActivity.this, "当前骑记正在骑行中，不能分享!", Toast.LENGTH_SHORT).show();
			return ;
		}
		
		if ( rl.getRemoteId() == null || rl.getRemoteId() == 0 ) {
			Toast.makeText(DetailActivity.this, "当前骑记未同步，请先同步数据!", Toast.LENGTH_SHORT).show();
			return ;
		}

		
		String shareUrl = Constants.WEB_DOMAIN+"/ridingline/"+rl.getId();
		String shareTitle = rl.getTitle();
		
		String tStr = this.getResources().getString(R.string.stat_times);
        int[] time = DateUtils.duration(rl.getTotalTime() * 1000);
        String tNewStr = String.format(tStr, time[1], time[2], time[3]);
		String shareContent = "总里程："+df.format(rl.getTotalMileage() / 1000)+"km"+";总时长："+tNewStr;
		if ( rl.getCreator() != null && !TextUtils.isEmpty(rl.getCreator().getUserName())) {
			shareContent = shareContent+"(来自"+rl.getCreator().getUserName()+"的骑记)";
		}
		
		Umeng.getConfig().setPlatforms(SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE
				, SHARE_MEDIA.SINA, SHARE_MEDIA.TENCENT, SHARE_MEDIA.RENREN, SHARE_MEDIA.SMS);
		
		Umeng.setShareContent(shareContent+shareUrl);
		Umeng.setAppWebSite(SHARE_MEDIA.RENREN, shareUrl);
		Umeng.setAppWebSite(shareUrl);
		Umeng.setShareImage(new UMImage(this, R.drawable.ic_launcher));
		Umeng.setShareMedia(new UMImage(this, R.drawable.ic_launcher));
		
		QQShareContent qqShareContent = new QQShareContent(); //设置分享文字
		qqShareContent.setShareContent(shareContent);
		qqShareContent.setTitle(shareTitle); //设置分享title
		qqShareContent.setShareImage(new UMImage(this, R.drawable.ic_launcher)); //设置分享图片
		qqShareContent.setTargetUrl(shareUrl); //设置点击分享内容的跳转链接
		Umeng.setShareMedia(qqShareContent);
		
		QZoneShareContent qzone = new QZoneShareContent();
		qzone.setShareContent(shareContent);  //设置分享文字
		qzone.setTitle(shareUrl);  //设置分享内容的标题
//				qzone.setShareImage(new UMImage(this, "http://onriding.cc/favicon_64.ico"));  //设置分享图片, 服务器上要放一个圆角的
		qzone.setShareImage(new UMImage(this, R.drawable.ic_launcher));  //设置分享图片
		qzone.setTargetUrl(shareUrl);  //设置点击消息的跳转URL,前期直接写APP下载地址
		Umeng.setShareMedia(qzone);
		
		
		//QQSSO 参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, Constants.SECURITY_QQ_APP_ID,
				Constants.SECURITY_QQ_APP_SECRET);
		qqSsoHandler.addToSocialSDK(); 
				
		//QQ空间SSO 参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, Constants.SECURITY_QQ_APP_ID,
				Constants.SECURITY_QQ_APP_SECRET);
		qZoneSsoHandler.addToSocialSDK();
		
		SmsHandler smsHandler = new SmsHandler();
		smsHandler.addToSocialSDK();
		
//				// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(this, Constants.SECURITY_WEIXIN_APP_ID, Constants.SECURITY_WEIXIN_APP_SECRET);
		wxHandler.showCompressToast(false);  //解决图片大小超过32k的BUG
		wxHandler.addToSocialSDK();
		
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this, Constants.SECURITY_WEIXIN_APP_ID, Constants.SECURITY_WEIXIN_APP_SECRET);
		wxCircleHandler.showCompressToast(false);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		
		
		//设置新浪SSO handler
		Umeng.getConfig().setSsoHandler(new SinaSsoHandler());
		
		//设置腾讯微博SSO handler
		Umeng.getConfig().setSsoHandler(new TencentWBSsoHandler());
		
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(this,
				Constants.SECURITY_RENREN_APP_ID, Constants.SECURITY_RENREN_KEY,
				Constants.SECURITY_RENREN_KEY_SECRET);
		Umeng.getConfig().setSsoHandler(renrenSsoHandler);
		Umeng.openShare(this, false);
	}
	
	private void continueRiding() {
		if ( RidingService.now_rlId != 0 ) {
			Toast.makeText(DetailActivity.this, "当前有正在进行的骑记！", Toast.LENGTH_SHORT).show();
			return ;
		} else {
			
			Intent intent = new Intent();
 			intent.setAction(RidingService.CTRL_CONTINUE);
 			intent.putExtra("rlId", rl.getId());
 			sendBroadcast(intent);
 			
 			isDealEnd = true;
 			
 			tvEndRiding.setVisibility(View.VISIBLE);
			tvContinue.setVisibility(View.GONE);
			btnOK.setVisibility(View.GONE);
 			
//			Intent intent = new Intent(DetailActivity.this, MainActivity.class);
//			intent.putExtra("act", "act_rl_continue");
//			intent.putExtra("rlId", rl.getId());
//			startActivity(intent);
//			this.finish();
		}
	}
	
	private void dialogStopRiding() {
		CustomDialog dialog = new CustomDialog(DetailActivity.this, R.style.dialog_style
				, R.layout.dialog, R.string.dialog_stop_riding, new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch(v.getId()){
				case R.id.confirm_btn:

					endRiding();
					
					break;
				default:
		            break;
				}
			}
		});
        dialog.show();
	}
	
	private void endRiding() {
		if ( rl.getId().intValue() == RidingService.now_rlId ) {
			//通知后台服务停止
			Intent intent = new Intent();
			intent.setAction(RidingService.CTRL_STOP);
			intent.putExtra("rlId", rl.getId());
			sendBroadcast(intent);
			
			waiteEnd = true;
			cp = ColaProgress.show(DetailActivity.this, "", true, false, null);
			cp.show();
		} else {
			//这里有BUG，如果一个骑记没有结束，点击 继续(进入到主界面)-->历史记录(进入到历史记录界面)-->点击当前要继续的骑记-->点击结束-->骑记结束但没有修改主界面的状态
			//解决办法就是直接在详情页面发送继续骑记的行为通知给骑行服务###
			DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
			try {
				rl.setIsNow(false);
				Date endTime = DateUtils.addTimes(rl.getStartTime(), rl.getTotalTime());
				rl.setEndTime(endTime);
				
				DbModel dbModel = dbu.findDbModelFirst(Selector.from(LinePoint.class).select("COUNT(id_) AS num,SUM(speed_) AS totalGpsSpeed").where("ridingline_id", "==", rl.getId()));
				if (dbModel != null && !dbModel.getDataMap().isEmpty()) {
					int num = dbModel.getInt("num");
					float totalGpsSpeed = 0;
					if ( !dbModel.isEmpty("totalGpsSpeed") ) {
						totalGpsSpeed = dbModel.getFloat("totalGpsSpeed");
					}
					
					float avgGpsSpeed = totalGpsSpeed / num;
					rl.setAvgGpsSpeed(avgGpsSpeed);
					dbu.update(rl, "isNow_","avgGpsSpeed_","endTime_");
				} else {
					dbu.update(rl, "isNow_","endTime_");
				}

				initData(rl.getId());
				
				statUserData(this);
				isDealEnd = true;
			} catch (DbException e) {
				Toast.makeText(DetailActivity.this, "结束骑记失败~_~", Toast.LENGTH_SHORT).show();
				Log.e(TAG, e.getMessage());
			}
		}
	}
	
	private void dialogDeleteRiding() {
		CustomDialog dialog = new CustomDialog(DetailActivity.this, R.style.dialog_style
				, R.layout.dialog, R.string.dialog_delete_riding, new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch(v.getId()){
				case R.id.confirm_btn:

					deleteRiding();
					
					break;
				default:
		            break;
				}
			}
		});
        dialog.show();
	}
	
	private void deleteRiding() {
		try {
			DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
			dbu.delete(LinePoint.class, WhereBuilder.b("ridingline_id", "=", rl.getId()));  //先删除坐标点
			if ( rl.getRemoteId() == null || rl.getRemoteId() == 0) {  //如果这条数据还没上传到服务器则直接删除本地数据
				dbu.deleteById(RidingLine.class, rl.getId());
			} else {
				rl.setCrudStatus(RidingLine.CRUD_STATUS_DELETE);
				rl.setSendStatus(0);
				dbu.update(rl, "crudStatus_","sendStatus_");
			}
			
			statUserData(this);
			
			Toast.makeText(DetailActivity.this, "删除成功^_^", Toast.LENGTH_SHORT).show();
			setResult(RESULT_OK);
			this.finish() ;
		} catch (DbException e) {
			Toast.makeText(DetailActivity.this, "删除失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	public class RidingReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(RidingService.UPDATE_STAT)) {
				Log.i(TAG, "---UPDATE_STAT.通知---");
				
				long rlId = intent.getLongExtra("now_rlId", 0l);
				
				if ( rl.getId().intValue() != rlId ) {
					if ( ridingReceiver != null ) {
						DetailActivity.this.unregisterReceiver(ridingReceiver);
					}
				} else {
					float totalMileage = intent.getFloatExtra("totalMileage", 0.00f);
					int totalPoint = intent.getIntExtra("totalPoint", 0);
					long totalTime = intent.getLongExtra("totalTime", 0l);
					long validTime = intent.getLongExtra("totalValidTime", 0l);
					
					if (totalMileage > 0) {
						tvMileage.setText(df.format(totalMileage / 1000));
					} else {
						tvMileage.setText(String.valueOf("0.00"));
					}
					
					tvPoint.setText(String.valueOf(totalPoint));
					String tStr = getResources().getString(R.string.stat_times);
					int[] time = DateUtils.duration(totalTime * 1000);
			        String tNewStr = String.format(tStr, time[1], time[2], time[3]);
					tvTotalTime.setText(String.valueOf(tNewStr));
					
					String tStr1 = getResources().getString(R.string.stat_times);
					int[] time1 = DateUtils.duration(validTime * 1000);
			        String tNewStr1 = String.format(tStr1, time1[1], time1[2], time1[3]);
					tvValidTime.setText(tNewStr1);
					
					long pauseTime = totalTime-validTime;
					String tStr3 = getResources().getString(R.string.stat_times);
			        int[] time3 = DateUtils.duration(pauseTime * 1000);
			        String tNewStr3 = String.format(tStr3, time3[1], time3[2], time3[3]);
					tvPauseTime.setText(tNewStr3);
				}
			} else if (action.equals(RidingService.UPDATE_SPEED)) {
//				float maxSpeed = intent.getFloatExtra("maxSpeed", 0l);
//				float avgSpeed = intent.getFloatExtra("avgSpeed", 0l);
				float speed = intent.getFloatExtra("speed", 0l);
				float maxGpsSpeed = intent.getFloatExtra("maxGpsSpeed", 0l);
//				String msg = maxSpeed+";"+avgSpeed+";"+maxGpsSpeed;
//					Toast.makeText(DetailActivity.this, "receive："+msg, Toast.LENGTH_SHORT).show();
				
				tvMaxSpeed.setText(String.valueOf(maxGpsSpeed));
				tvAvgSpeed.setText("--");
				tvCurSpeed.setText(String.valueOf(speed));
//				tvMaxGpsSpeed.setText(String.valueOf(maxGpsSpeed));
			} else if (action.equals(RidingService.RL_UPDATE)) {
				long rlId = intent.getLongExtra("now_rlId", 0l);
				if ( rl.getId().intValue() == rlId ) {
					
					String act = intent.getStringExtra("act");
					if ( "end".equals(act) ) {
						initData(rlId);
						
						tvEndRiding.setVisibility(View.GONE);
						tvContinue.setVisibility(View.GONE);
						btnOK.setVisibility(View.VISIBLE);
						
						if ( waiteEnd ) {
							cp.dismiss();
						}
						
						isDealEnd = true;
					}
				}
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    if ( resultCode == RESULT_OK ) {
	    	 String title = data.getStringExtra("title");
	    	 if ( !TextUtils.isEmpty(title) ) {
	    		 isUpadateOk = true;
	    		 tvLineTitle.setText(title);
	    	 }
	    }
	}
	
	@Override
	protected void onStop() {
		if (ridingReceiver != null) {
			this.unregisterReceiver(ridingReceiver);
		}
		super.onStop();
	}
	
	@Override
	public void onBackPressed() {
		endThis();
	}
	
	private void endThis() {
		if ( isDealEnd || isUpadateOk ) {
			setResult(RESULT_OK);
		}
		this.finish();
	}
	
	
}
